import { defineStore } from "pinia";
import { ref } from "vue";
import {
  type UserInfo,
  type MPWechatLoginParams,
  getPhoneNumber,
  mpWechatLogin,
} from "@/common/apis/user";

export const useUserStore = defineStore("user", () => {
  const userInfo = ref<UserInfo | null>(uni.getStorageSync("userInfo") || null);
  const token = ref<string | null>(uni.getStorageSync("token") || null);
  const isLogin = ref<boolean>(uni.getStorageSync("isLogin") || false);

  /**
   * @description 获取微信绑定手机号
   * @param {string} code - 微信登录获取的code
   * @returns {Promise<string>} 手机号
   */
  async function fetchGetPhoneNumber(code: string) {
    const response = await getPhoneNumber({ code });
    if (response) {
      return response.phone;
    }
  }

  /**
   * @description 微信小程序登录
   * @param {MPWechatLoginParams} params - 登录参数
   * @returns {Promise<boolean>} 登录成功返回true，否则返回false
   */
  async function fetchMpWechatLogin(
    params: MPWechatLoginParams
  ): Promise<boolean> {
    const response = await mpWechatLogin(params);
    if (response) {
      isLogin.value = true;
      token.value = response.token.access_token;
      userInfo.value = response.user;
      uni.setStorageSync("userInfo", response.user); // 存储用户信息
      uni.setStorageSync("token", response.token.access_token); // 存储token
      uni.setStorageSync("isLogin", true); // 存储登录状态
      return true;
    }
    return false; // 登录失败返回false
  }

  return {
    isLogin,
    userInfo,
    fetchGetPhoneNumber,
    fetchMpWechatLogin,
  };
});

export const useUserStoreHook = () => {
  const store = useUserStore();
  return store;
};
